 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SportStore.Models.Entities;
using SportStore.Framework;

namespace SportStore.Filters
{
    public class RoleFilterAttribute : AuthorizeAttribute
    {
        private string[] _authorizedRoles;
        public string[] AuthorizedRoles
        {
            get { return _authorizedRoles ?? new string[0]; }
            set { _authorizedRoles = value; }
        }
        public string RequestKey { get; set; }

        
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var user = SessionManager.User();
            var rs = from r in user.Roles join r1 in AuthorizedRoles on r.Name equals r1 select r;
            bool authorized = false;
            if (RequestKey != null)
            {
                var routeValue = filterContext.RequestContext.RouteData.Values[RequestKey]??filterContext.RequestContext.HttpContext.Request[RequestKey];
                int productId = int.Parse(routeValue.ToString());
                if (user.isOwner(productId))
                {
                    authorized = true;
                }
            }
                        
            if (rs.Count() > 0)
            {
                authorized = true;
            }

            if (!authorized) filterContext.Result = new RedirectResult("/Account/LogOn");
        }
    }
}